package com.lqw.vhr.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    /**
     * control + H 查看类的继承关系
     * @param authentication 当前用户的认证信息，例如UsernamePasswordAuthenticationToken(包含登陆后的信息)，AnonymousAuthenticationToken为对未登陆对象的分装
     * @param object
     * @param configAttributes 为CustomFilterInvocationSecurityMetadataSource传过来的所需要的认证信息
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (authentication instanceof AnonymousAuthenticationToken) throw new AccessDeniedException("尚未登录，请登录!");
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if (needRole.equals("ROLE_LOGIN")) return;
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //当满足其中一个角色时则表示有权访问这个接口
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
